import { memo } from "react";
import { InboxOutlined } from "@ant-design/icons";
import Dragger from "antd/es/upload/Dragger";
import { AUTH_TOKEN } from "../../constant";
import { message } from "antd";
import ImgCrop from "antd-img-crop";
import { RcFile } from "antd/es/upload";

const UploadV1 = memo((props) => {
  const title: string = props.title as string;
  const id: string = props.id as string;
  const refetch: () => void = props.refetch as () => void;
  const token: string =
    localStorage.getItem(AUTH_TOKEN) || sessionStorage.getItem(AUTH_TOKEN);

  const upLoadChange = (value) => {
    if (value.event?.percent === 100) {
      try {
        refetch();
        void message.success("修改头像成功");
        location.reload();
        return;
      } catch (err) {
        void message.success("修改失败,请检查网络！");
      }
    }
  };
  const beforeUpload = (file: RcFile) => {
    const isIMG =
      file.type === "image/png" ||
      file.type === "image/jpeg" ||
      file.type === "image/jpg";
    if (!isIMG) {
      void message.error("请上传正确的文件格式（png,jpeg,jpg,jiff）!");
      return false;
    }
    return true;
  };

  return (
    <ImgCrop
      rotationSlider
      aspect={1}
      beforeCrop={(file) => {
        return beforeUpload(file);
      }}
    >
      <Dragger
        {...props}
        accept="image/png,image/jpeg,image/jpg"
        progress
        type="line"
        maxCount={1}
        beforeUpload={beforeUpload}
        method="post"
        headers={{
          Authorization: "Bearer " + token,
        }}
        action={`${import.meta.env.VITE_BASE_URL}/upload/` + id + "/false"}
        onChange={(value) => upLoadChange(value)}
      >
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-hint">{title}</p>
      </Dragger>
    </ImgCrop>
  );
});

export default UploadV1;
